package com.sumer.psychology.microblog.resource;

import com.sumer.psychology.common.application.ApplicationServiceRegistry;
import com.sumer.psychology.common.resource.AbstractResource;
import com.sumer.psychology.microblog.application.command.CreateMicroBlogCommand;
import com.sumer.psychology.microblog.application.command.DeleteMicroBlogCommand;
import com.sumer.psychology.microblog.domain.model.MicroBlogId;

import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.util.Collections;

/**
 * 微博rest接口
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/9/26
 * Time: 8:33
 */
@Path("/v1/micro_blog/")
@Consumes(MediaType.APPLICATION_JSON)
public class MicroBlogResource extends AbstractResource {
    @Context
    private UriInfo uriInfo;

    @POST
    public Response addMicroBlog(CreateMicroBlogCommand aCreateMicroBlogCommand) {
        checkAuthorAndRole(aCreateMicroBlogCommand);

        MicroBlogId microBlogId = ApplicationServiceRegistry
                .microBlogApplicationService()
                .newMicroBlog(aCreateMicroBlogCommand);

        return Response.status(Response.Status.CREATED)
                .location(uriInfo.getAbsolutePath())
                .entity(Collections.singletonMap("_id", microBlogId.identity()))
                .build();
    }

    @DELETE
    @Path("{microBlogId}")
    public Response deleteMicroBlog(@PathParam("microBlogId") String microBlogId) {
        ApplicationServiceRegistry
                .microBlogApplicationService()
                .delete(new DeleteMicroBlogCommand(microBlogId));

        return Response.status(Response.Status.ACCEPTED).build();
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response find(
            @QueryParam("countPerPage") int countPerPage,
            @QueryParam("offset") int offset) {
        String results = ApplicationServiceRegistry
                .microBlogQueryApplicationService()
                .list(countPerPage, offset);

        return Response.ok(results).build();
    }

    @GET
    @Path("author/{authorId}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response findByAuthor(
            @PathParam("authorId") String authorId,
            @QueryParam("countPerPage") int countPerPage,
            @QueryParam("offset") int offset) {
        String results = ApplicationServiceRegistry
                .microBlogQueryApplicationService()
                .findByAuthor(authorId, countPerPage, offset);

        return Response.ok(results).build();
    }

    @GET
    @Path("{microBlogId}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response findOneMicroBlog(@PathParam("microBlogId") String microBlogId) {
        String result = ApplicationServiceRegistry
                .microBlogQueryApplicationService()
                .findOneMicroBlog(microBlogId);

        return Response.ok(result).build();
    }

}
